package com.home.ty_smart_home

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.thingclips.smart.android.base.ThingSmartSdk.getApplication
import com.thingclips.smart.home.sdk.ThingHomeSdk
import com.thingclips.smart.sdk.api.IDevListener
import com.thingclips.smart.android.ble.api.BleConfigType
import com.thingclips.smart.android.ble.api.LeScanSetting
import com.thingclips.smart.android.ble.api.ScanType
import com.thingclips.smart.android.common.utils.WiFiUtil
import com.thingclips.smart.android.device.bean.BoolSchemaBean
import com.thingclips.smart.android.device.bean.EnumSchemaBean
import com.thingclips.smart.android.device.bean.StringSchemaBean
import com.thingclips.smart.android.device.bean.ValueSchemaBean
import com.thingclips.smart.android.device.enums.DataTypeEnum
import com.thingclips.smart.android.user.api.ILoginCallback
import com.thingclips.smart.android.user.api.IRegisterCallback
import com.thingclips.smart.android.user.api.IResetPasswordCallback
import com.thingclips.smart.android.user.bean.User

import com.thingclips.smart.home.sdk.bean.HomeBean
import com.thingclips.smart.home.sdk.builder.ActivatorBuilder
import com.thingclips.smart.home.sdk.callback.IThingGetHomeListCallback
import com.thingclips.smart.home.sdk.callback.IThingHomeResultCallback
import com.thingclips.smart.home.sdk.callback.IThingResultCallback
import com.thingclips.smart.sdk.ThingBaseSdk.getApplication
import com.thingclips.smart.sdk.ThingSdk.getApplication
import com.thingclips.smart.sdk.api.*
import com.thingclips.smart.sdk.bean.DeviceBean
import com.thingclips.smart.sdk.bean.MultiModeActivatorBean
import com.thingclips.smart.sdk.enums.ActivatorModelEnum
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.*


/** TySmartHomePlugin */
class TySmartHomePlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

  // 新增
  private lateinit var mApplication: Application
  private lateinit var localBroadcastManager: LocalBroadcastManager
  private  lateinit var currentContext: Context

  private lateinit var activity: Activity

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ty_smart_home")
    channel.setMethodCallHandler(this)

    mApplication = flutterPluginBinding.applicationContext as Application
    currentContext = flutterPluginBinding.applicationContext

    // 初始化TuyaHome
    ThingHomeSdk.init(mApplication, "guvmjumr4prkc3vtyf8c", "rkhvphvvmavephnekwvpa5nmahukfj7f")

    // 初始化广播
    localBroadcastManager = LocalBroadcastManager.getInstance(flutterPluginBinding.applicationContext)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    
    when (call.method) {
      "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
      /// 登录
      "loginWithWIFI" -> loginApp(call, result)
      /// 注册
      "registerWithWIFI" -> registerApp(call, result)
      /// 获取验证码
      "vertificateWithWIFI" -> getVertificateCode(call, result)
      /// 重置密码
      "resetPwdWithWIFI" -> resetPwdByPhone(call, result)
      /// 以 UID 形式登录
      "loginWithUID" -> loginAppWithUID(call, result)
      /// 以 UID 形式注册
      "registerWithUID" -> registerAppWithUID(call, result)
      /// 以UID形式登录, 如果未登录过则进行注册
      "loginOrRegisterWithUid" -> loginOrRegisterWithUid(call, result)
      /// 获取设备列表
      "getDeviceList" -> getHomeList(call, result)
      "modifyDeviceName" -> modifyDeviceName(call, result)
      "removeDeviceInfo" -> removeDeviceInfo(call, result)
      "getWIFIName" -> getWIFIName(call, result)
      "getHomeID" -> getHomeID(call, result)
      "commitEZModeAction" -> commitEZModeAction(call, result)
      "startLocation" -> startLocation(call, result)
      "go2WIFISetting" -> go2WIFISetting()
      "configWithDeviceID" -> configWithDeviceID(call, result)
      "loadHistoryData" -> loadHistoryData(call, result)
      /// 修改设备DP的值
      "updateDeviceDPS" -> updateDeviceDPS(call, result)
      /// 向其他用户发送共享设备的邀请
      "inviteShare" -> inviteShare(call, result)
      /// 确认分享邀请
      "confirmShareInviteShare" -> confirmShareInviteShare(call, result)
      /// 移除主动共享的设备
      "disableDevShare" -> disableDevShare(call, result)
      else -> result.notImplemented()

    }
  }
  
  fun go2WIFISetting() {
    openSettings(Settings.ACTION_WIFI_SETTINGS)
  }

  /*
    监听设备信息
   */
  fun configWithDeviceID(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val devId = args["deviceId"] as String;
    val device = ThingHomeSdk.newDeviceInstance(devId)
    device.registerDevListener(object : IDevListener {
      // dp 数据更新
      override fun onDpUpdate(devId: String?, dpStr: String?) {
        if (dpStr != null && devId != null) {
          LCLog("Android_dp 数据更新: $dpStr");
          val result = JSON.parseObject(dpStr, Map::class.java);

          var tempValue = 0
          var humiValue = 0
          val temp = result["102"] // 温度
          val humi = result["110"] // 湿度
          if(temp != null) {
            tempValue = temp as Int
          }
          if (humi != null) {
            humiValue = humi as Int
          }

          val intent = Intent("com.example.dpInfoStr")
          intent.putExtra("temp", "$tempValue") //发送数据
          intent.putExtra("humi", "$humiValue") //发送数据
          intent.putExtra("devId", "${devId}") //发送数据
          localBroadcastManager.sendBroadcast(intent) //发送本地广播
        };
      }
      override fun onRemoved(devId: String?) {

      }
      // 设备上下线回调。如果设备断电或断网，服务端将会在3分钟后回调到此方法
      override fun onStatusChanged(devId: String?, online: Boolean) {

      }
      override fun onNetworkStatusChanged(devId: String?, status: Boolean) {

      }
      override fun onDevInfoUpdate(devId: String?) {

      }
    })

  }

  // 登录(账号密码)
  // https://developer.tuya.com/cn/docs/app-development/usermanage?id=Ka69qtzy9l8nc
  fun loginApp(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val number = args["phoneNumber"] as String;
    val password = args["password"] as String;

    ThingHomeSdk.getUserInstance().loginWithPhonePassword(code, number, password, object : ILoginCallback {
      override fun onSuccess(user: User?) {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("登录失败: $error, errorcode: $code")
      }
    });
  }
  // 登录(UID, 已经有自己的账号体系的场景)
  fun loginAppWithUID(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val uid = args["uid"] as String;
    val password = args["password"] as String;

    ThingHomeSdk.getUserInstance().loginWithUid(code, uid, password, object : ILoginCallback {
      override fun onSuccess(user: User?) {
        result.success(mapOf("result" to "1", "username" to user!!.username, "uid" to user.uid ));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("登录失败: $error, errorcode: $code")
      }
    });
  }

  // 注册(账号密码)
  fun registerApp(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val number = args["phoneNumber"] as String;
    val password = args["password"] as String;
    val vertificate = args["vertificate"] as String;

    ThingHomeSdk.getUserInstance().registerAccountWithPhone(code, number, password, vertificate, object : IRegisterCallback{
      override fun onSuccess(user: User?) {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("注册失败: $error, errorcode: $code")
      }

    })
  }
  // 注册(UID)
  fun registerAppWithUID(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val uid = args["uid"] as String;
    val password = args["password"] as String;

    ThingHomeSdk.getUserInstance().registerAccountWithUid(code, uid, password, object : IRegisterCallback{
      override fun onSuccess(user: User?) {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("注册失败: $error, errorcode: $code")
      }

    })
  }

  // 用户 UID（User ID）登录采用注册和登录为一体的接口，如果注册了账号就自动登录，如果没有注册就自动注册并且登录。
  fun loginOrRegisterWithUid(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val uid = args["uid"] as String;
    val password = args["password"] as String;

    // UID 登录
    ThingHomeSdk.getUserInstance()
      .loginOrRegisterWithUid(code, uid, password, object : ILoginCallback {
        override fun onSuccess(user: User) {
          result.success(mapOf("result" to "1", "username" to user.username, "uid" to user.uid ));
        }

        override fun onError(code: String, error: String) {
          result.success(mapOf("result" to error, "code" to code));
          LCLog("涂鸦登录失败: $error, errorcode: $code")
        }
      })
  }

  // 获取验证码
  fun getVertificateCode(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val number = args["phoneNumber"] as String;
    val type = args["type"] as Int;

    /**
    0: 用于登录,
    1: 用于手机号注册,
    2: 用于重置密码
     */
    ThingHomeSdk.getUserInstance().sendBindVerifyCode(code, number, object : IResultCallback{
      override fun onSuccess() {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("获取验证码失败: $error, errorcode: $code")
      }

    })
  }

  // 重置密码
  fun resetPwdByPhone(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val code = args["code"] as String;
    val number = args["phoneNumber"] as String;
    val password = args["password"] as String;
    val vertificate = args["vertificate"] as String;

    ThingHomeSdk.getUserInstance().resetPhonePassword(code, number, vertificate, password, object : IResetPasswordCallback{
      override fun onSuccess() {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("重置密码失败: $error, errorcode: $code")
      }

    })
  }

  // 获取的家庭列表
  fun getHomeList(call: MethodCall, result: Result) {
//    LCLog("获取家庭列表数据")
    ThingHomeSdk.getHomeManagerInstance().queryHomeList(object : IThingGetHomeListCallback {
      override fun onSuccess(homeBeans: MutableList<HomeBean>?) {

        LCLog("家庭列表个数: ${homeBeans?.size}")  // 这里我们只使用首个家庭数据, 默认一个账号只会创建一个家庭.

        if (homeBeans != null) {
          if (homeBeans.size > 0) {

            for(homeBean in homeBeans) {
              LCLog("家庭名称: ${homeBean.name}, HomeID: ${homeBean.homeId}" )
            }

            val homeId = homeBeans.get(0).homeId;
            // 获得家庭详细数据
            ThingHomeSdk.newHomeInstance(homeId).getHomeDetail(object : IThingHomeResultCallback {
              override fun onSuccess(bean: HomeBean?) {
                LCLog("设备个数: ${bean?.deviceList?.size}, HomeID: ${homeId}")

                if (bean != null) {
                  val dataArr = ArrayList<Map<String, Any>>()
                  for (ele in bean.deviceList) {
                    LCLog("测试设备: ${ele.devId} ${ele.dps["102"]}")

                    if (ele.devId.contains("vdevo")) {  // 不添加测试设备

                    } else {
                      val map = TreeMap<String, Any>()
                      map["devId"] = ele.devId;
                      map["name"] = ele.name
                      map["isOnline"] = ele.isOnline
                      map["dps"] = ele.dps
//                      map["serialNumber"] = ele.dps["102"] as String
                      map["homeId"] = "${homeId}"
//                      map["dpCodes"] = ele.dpCodes
                      dataArr.add(map)
                    }
                  }
                  result.success(dataArr)
                }
              }

              override fun onError(errorCode: String?, errorMsg: String?) {
                LCLog("获取家庭详细信息失败: $errorMsg")
              }
            })

          } else {  // 创建一个家庭
            ThingHomeSdk.getHomeManagerInstance().createHome("hangzhou's home", 0.0, 0.0, "hangzhou", listOf("bedroom"),
                    object : IThingHomeResultCallback{
                      override fun onSuccess(bean: HomeBean?) {
                        if (bean != null) {
                          val dataArr = ArrayList<Map<String, Any>>()
                          val map = mapOf("homeID" to "${bean.homeId}", "devID" to "")
                          dataArr.add(map)
                          result.success(dataArr)
                        }
                      }

                      override fun onError(errorCode: String?, errorMsg: String?) {
                        LCLog("添加家庭: $errorMsg")
                      }
                    }
            )
          }
        }
      }

      override fun onError(errorCode: String?, error: String?) {
        print("获取家庭列表: $error");
      }
    })
  }

  // 修改名称
  fun modifyDeviceName(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val devId = args["devId"] as String;
    val name = args["name"] as String;
    val device = ThingHomeSdk.newDeviceInstance(devId)
    device.renameDevice(name, object : IResultCallback{
      override fun onSuccess() {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("修改名称失败: $error, errorcode: $code")
      }
    })
  }

  // 删除设备
  fun removeDeviceInfo(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val devId = args["devId"] as String;
    val device = ThingHomeSdk.newDeviceInstance(devId)
    device.removeDevice(object : IResultCallback{
      override fun onSuccess() {
        result.success(mapOf("result" to "1"));
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("删除设备失败: $error, errorcode: $code")
      }

    })
  }

  // 修改 DPS 数据
  fun updateDeviceDPS(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val devId = args["devId"] as String;
    val dpKey = args["dpKey"] as String;  // dp code
    var dpValue = args["dpValue"];  // 任意类型

    var dpId = ""
    // 更改数据类型
    val schemaMap = ThingHomeSdk.getDataInstance().getSchema(devId)

    LCLog("修改DPS数据: $devId, $dpKey, $dpValue");
    LCLog("修改DPS数据2: $schemaMap");

    if (schemaMap == null){
      result.success(mapOf("result" to "请重新进行设备配网"));
      return
    }

    for(dpBean in schemaMap.values) {
//      LCLog("schemaMap: ${dpBean.id}, ${dpBean.code}")
      if(dpBean.code == dpKey) {
        dpId = dpBean.id
        if(dpBean.type == DataTypeEnum.OBJ.type) {
          when(dpBean.schemaType) {
            BoolSchemaBean.type -> {}
            EnumSchemaBean.type -> { dpValue = dpValue.toString() }
            StringSchemaBean.type -> {}
            ValueSchemaBean.type -> {}
          }
        }else if(dpBean.type == DataTypeEnum.RAW.type) {}  // 此处用不到
      }
    }

//    val deviceBean = ThingHomeSdk.getDataInstance().getDeviceBean(devId);
//
//    if(deviceBean?.dps?.containsKey(dpId) == true) {
//      deviceBean.dps[dpId] = dpValue
//      LCLog("deviceBean: ${deviceBean.dps}, dpId: ${dpId}, dpValue: ${dpValue}")
//    }

    val device = ThingHomeSdk.newDeviceInstance(devId)
//    val dpsStr = JSONObject.toJSONString(deviceBean?.dps)

    val map = HashMap<String, Any>()
    map[dpId] = dpValue as Any
    val dpsStr = JSONObject.toJSONString(map)
    LCLog("dpsStr: ${dpsStr}")
    device.publishDps(dpsStr, object : IResultCallback{
      override fun onSuccess() {
        result.success(mapOf("result" to "1"));
        LCLog("修改设备 DPKey: $dpKey 成功");
      }

      override fun onError(code: String?, error: String?) {
        result.success(mapOf("result" to error, "code" to code));
        LCLog("修改设备 DPKey: $dpKey 失败: $error, errorcode: $code");
      }

    })
  }

  // 获取WIFI名称
  fun getWIFIName(call: MethodCall, result: Result) {
//    val ssid = WiFiUtil.getCurrentSSID(ThingHomeSdk.getApplication());
//    Log.d("wifi名称", ssid)
//    result.success(mapOf("result" to ssid))
  }

  // 获取HomeID
  fun getHomeID(call: MethodCall, result: Result) {
    ThingHomeSdk.getHomeManagerInstance().queryHomeList(object : IThingGetHomeListCallback{
      override fun onSuccess(homeBeans: MutableList<HomeBean>?) {
        if (homeBeans != null) {
          if (homeBeans.size > 0) {
            val homeId = homeBeans.get(0).homeId;
            result.success("$homeId");
            
          } else {  // 创建一个家庭
            ThingHomeSdk.getHomeManagerInstance().createHome("hangzhou's home", 0.0, 0.0, "hangzhou", listOf("bedroom"),
                    object : IThingHomeResultCallback{
                      override fun onSuccess(bean: HomeBean?) {
                        if (bean != null) {

                          result.success("${bean.homeId}");
                        }
                      }

                      override fun onError(errorCode: String?, errorMsg: String?) {
                        print("添加家庭: $errorMsg");
                      }
                    }
            )
          }
        }
      }

      override fun onError(errorCode: String?, error: String?) {
        print("获取家庭列表: $error");
      }
    })
  }

  // 开始配网
  fun commitEZModeAction(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    val ssid = args["ssid"] as String;
    val password = args["password"] as String;
    val homeIDStr = args["homeID"] as String
    val homeID = homeIDStr.toLong()

    LCLog("homeID: ${homeID} $ssid $password ")

    ThingHomeSdk.getActivatorInstance().getActivatorToken(homeID, object : IThingActivatorGetToken{
      override fun onSuccess(token: String?) {
        LCLog("配网Token: ${token}")

        if (token != null) {
//          startConfigBLEMode(ssid, password, token, homeID)
          startConfigEZMode(ssid, password, token)
//          startConfigAPMode(ssid, password, token)
          return

          ThingHomeSdk.getActivatorInstance().newActivator(ActivatorBuilder()
                  .setContext(currentContext)
                  .setSsid(ssid)
                  .setPassword(password)
                  .setTimeOut(100)
                  .setActivatorModel(ActivatorModelEnum.THING_AP)  // TY_EZ
                  .setToken(token)
                  .setListener(object : IThingSmartActivatorListener{
                    override fun onStep(step: String?, data: Any?) {
                      if (step != null && data != null) {
                        LCLog("配网-step-: $step, data: $data")
                      }
                    }

                    override fun onActiveSuccess(devResp: DeviceBean?) {
                      if (devResp != null) { // 配网成功

                        val intent = Intent("com.example.wifi")
                        intent.putExtra("result", "1") //发送数据
                        localBroadcastManager.sendBroadcast(intent) //发送本地广播

                        LCLog("配网成功")
                      }
                    }

                    override fun onError(errorCode: String?, errorMsg: String?) {
                      if (errorMsg != null) {  // 配网失败
                        val intent = Intent("com.example.wifi")
                        intent.putExtra("result", "0")
                        localBroadcastManager.sendBroadcast(intent)
                        
                        LCLog("errorMsg: $errorMsg errorCode: $errorCode")
                      }
                    }

                  })
          
          ).start()   // 开始配网

        }

      }

      override fun onFailure(errorCode: String?, errorMsg: String?) {
        print("获取Token失败: $errorMsg");
      }

    })

  }

  fun startLocation(call: MethodCall, result: Result) {
//    showLocationError()
  }

  fun loadHistoryData(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;
    
    LCLog("加载历史数据: $args")
    val devId = args["devId"] as String;
    val dpIds = "102,110";
    var offset = args["offset"] as Int;
    val limit = 10000;
    val startTime = args["startTime"] as String // 开始时间戳
    val endTime = args["endTime"] as String // 结束时间戳
    val sortType = "DESC"  // 顺序, 时间从大到小
    
    val map = TreeMap<String, Any>()
    map["devId"] = devId;
    map["dpIds"] = dpIds;
    map["offset"] = offset;
    map["limit"] = limit;
    map["startTime"] = startTime;
    map["endTime"] = endTime;
    map["sortType"] = sortType;
    
    ThingHomeSdk.getRequestInstance().requestWithApiName("tuya.m.smart.operate.all.log", "1.0", map, DpModel::class.java, object : IThingDataCallback<DpModel> {
      override fun onSuccess(data: DpModel) {
        LCLog("Android获取历史数据成功: ${data.dps}");
        val dataArr = ArrayList<Map<String, Any>>()
        for (ele in data.dps) {

          val map = TreeMap<String, Any>()
          map["value"] = ele.value;
          map["dpId"] = ele.dpId
          map["timeStamp"] = ele.timeStamp
          dataArr.add(map)
        }
        
        val resultMap = TreeMap<String, Any>()
        resultMap["dataArr"] = dataArr
        resultMap["hasNext"] = data.isHasNext
        result.success(resultMap)
      }

      override fun onError(errorCode: String?, errorMessage: String?) {
        LCLog("Android获取历史数据出错: $errorCode, $errorMessage");
      }
    })
    
  }

  private fun openSettings(url: String) {
    try {
      this.activity.startActivity(Intent(url))
    } catch(e:Exception) {
      // Default to APP Settings if setting activity fails to load/be available on device
      openAppSettings()
    }
  }
  private fun openAppSettings() {
    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    val uri = Uri.fromParts("package", this.activity.packageName, null)
    intent.data = uri
    this.activity.startActivity(intent)
  }

  /// 向其他用户发送共享设备的邀请
  fun inviteShare(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;

    val devId = args["devId"] as String; // 设备ID
    val code = args["code"] as String;   // 国家码
    val uid = args["uid"] as String;     // 用户ID

    ThingHomeSdk.getDeviceShareInstance()
      .inviteShare(devId, uid, code, object : IThingResultCallback<Int?> {
        override fun onSuccess(data: Int?) {
          result.success(mapOf("result" to "$data"));
          LCLog("发送共享设备的邀请: 成功")
        }
        override fun onError(errorCode: String, errorMessage: String) {
          LCLog("发送共享设备的邀请: $errorMessage, errorcode: $errorCode")
          result.success(mapOf("result" to "0", "code" to errorCode));
        }
      })
  }
  /// 确认分享邀请
  fun confirmShareInviteShare(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;

    val shareId = args["shareId"] as Int; // 分享ID

    ThingHomeSdk.getDeviceShareInstance()
      .confirmShareInviteShare(shareId, object : IResultCallback {
        override fun onError(code: String?, error: String?) {
          LCLog("确认分享邀请: $error, errorcode: $code")
          result.success(mapOf("result" to "0", "code" to code));
        }
        override fun onSuccess() {
          LCLog("确认分享邀请: 成功")
          result.success(mapOf("result" to "1"));
        }
      })
  }

  /// 移除主动共享的设备
  fun disableDevShare(call: MethodCall, result: Result) {
    val args = call.arguments as Map<*, *>;

    val devId = args["devId"] as String; // 设备ID
    val memberId = args["tyUID"] as Long; // 成员ID

    ThingHomeSdk.getDeviceShareInstance()
      .disableDevShare(devId, memberId, object : IResultCallback {
        override fun onError(code: String?, error: String?) {
          LCLog("移除主动共享的设备: $error, errorcode: $code");
          result.success(mapOf("result" to "0", "code" to code));
        }
        override fun onSuccess() {
          result.success(mapOf("result" to "1"));
        }
      })


  }

  fun LCLog(msg: String) {
    Log.d("TyPlugin", msg)
  }

  /// EZ 配网
  fun startConfigEZMode(ssid: String, password: String, token: String) {
    ThingHomeSdk.getActivatorInstance().newMultiActivator(ActivatorBuilder()
      .setContext(currentContext)
      .setSsid(ssid)
      .setPassword(password)
      .setTimeOut(100)
      .setActivatorModel(ActivatorModelEnum.THING_EZ)  // TY_EZ
      .setToken(token)
      .setListener(object : IThingSmartActivatorListener{
        override fun onStep(step: String?, data: Any?) {
          if (step != null && data != null) {
            LCLog("配网-step-: $step, data: $data")
          }
        }

        override fun onActiveSuccess(devResp: DeviceBean?) {
          if (devResp != null) { // 配网成功

            val intent = Intent("com.example.wifi")
            intent.putExtra("result", "1") //发送数据
            localBroadcastManager.sendBroadcast(intent) //发送本地广播

            LCLog("配网成功")
          }
        }

        override fun onError(errorCode: String?, errorMsg: String?) {
          if (errorMsg != null) {  // 配网失败
            val intent = Intent("com.example.wifi")
            intent.putExtra("result", "0")
            localBroadcastManager.sendBroadcast(intent)

            LCLog("errorMsg: $errorMsg errorCode: $errorCode")
          }
        }

      })

    ).start()
  }

  /// AP 配网
  fun startConfigAPMode(ssid: String, password: String, token: String) {
    val builder = ActivatorBuilder()
      .setContext(currentContext)
      .setSsid(ssid)
      .setPassword(password)
      .setTimeOut(100)
      .setActivatorModel(ActivatorModelEnum.THING_AP)
      .setToken(token)
      .setListener(object : IThingSmartActivatorListener{
        override fun onStep(step: String?, data: Any?) {
          if (step != null && data != null) {
            LCLog("配网-step-: $step, data: $data")
          }
        }

        override fun onActiveSuccess(devResp: DeviceBean?) {
          if (devResp != null) { // 配网成功

            val intent = Intent("com.example.wifi")
            intent.putExtra("result", "1") //发送数据
            localBroadcastManager.sendBroadcast(intent) //发送本地广播

            LCLog("配网成功")
          }
        }

        override fun onError(errorCode: String?, errorMsg: String?) {
          if (errorMsg != null) {  // 配网失败
            val intent = Intent("com.example.wifi")
            intent.putExtra("result", "0")
            localBroadcastManager.sendBroadcast(intent)

            LCLog("errorMsg: $errorMsg errorCode: $errorCode")
          }
        }

      });

    ThingHomeSdk.getActivatorInstance().newActivator(builder).start()
  }

  /// BLE配网
  fun startConfigBLEMode(ssid: String, password: String, token: String, homeId: Long) {

    val scanSetting = LeScanSetting.Builder()
      .setTimeout(60000) // 扫描的超时时间：ms
      .addScanType(ScanType.SINGLE) // 若需要扫描蓝牙设备，则只需要添加 ScanType.SINGLE
      .build()

    LCLog("开始扫描蓝牙设备")
    // 开始扫描
    ThingHomeSdk.getBleOperator().startLeScan(scanSetting) {
      // 回调扫描的结果 TODO

      LCLog("待配网设备类型: ${it.configType}")
      if (it.configType == BleConfigType.CONFIG_TYPE_WIFI.type) {

        val multiModeActivatorBean = MultiModeActivatorBean();
        // mScanDeviceBean 来自于扫描回调的 ScanDeviceBean
        multiModeActivatorBean.deviceType = it.getDeviceType(); // 设备类型
        multiModeActivatorBean.uuid = it.getUuid(); // 设备 uuid
        multiModeActivatorBean.address = it.getAddress(); // 设备地址
        multiModeActivatorBean.mac = it.getMac(); // 设备 mac
        multiModeActivatorBean.ssid = ssid; // Wi-Fi SSID
        multiModeActivatorBean.pwd = password; // Wi-Fi 密码
        multiModeActivatorBean.token = token; // 获取的 Token
        multiModeActivatorBean.homeId = homeId; // 当前家庭 homeId
        multiModeActivatorBean.timeout = 120000; // 超时时间

        // 开始配网
        ThingHomeSdk.getActivator().newMultiModeActivator()
          .startActivator(multiModeActivatorBean, object : IMultiModeActivatorListener {
            override fun onSuccess(deviceBean: DeviceBean) {
              // 配网成功
              val intent = Intent("com.example.wifi")
              intent.putExtra("result", "1") //发送数据
              localBroadcastManager.sendBroadcast(intent) //发送本地广播

              LCLog("配网成功")
            }

            override fun onFailure(code: Int, msg: String, handle: Any) {
              // 配网失败
              val intent = Intent("com.example.wifi")
              intent.putExtra("result", "0")
              localBroadcastManager.sendBroadcast(intent)

              LCLog("errorMsg: $msg errorCode: $code")
            }
          })
      }


    }

  }


  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  // activity 相关方法
  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    this.activity = binding.activity
  }

  override fun onDetachedFromActivityForConfigChanges() {
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    this.activity = binding.activity
  }

  override fun onDetachedFromActivity() {
  }
  
}
